<?php
declare (strict_types=1);

namespace app\model;

use app\model\OrdersGoods;
use think\facade\Db;
use think\Model;

/**
 * @mixin \think\Model
 */
class Orders extends Model
{
    //
    protected $table = 'order';

    //创建订单
    public static function createOrder($data)
    {
        $orderGoodsData = [];
        Db::startTrans();
        try {
            $order = Orders::create([
                'order_no' => $data['third_sn'],
                'primary_address' => $data['primary_address'],
                'address' => $data['address'],
                'consignee' => $data['consignee'],
                'mobile' => $data['mobile'],
                'remark' => $data['remark']??"",
                'create_time' => $data['create_time'],
                'status' => 1
            ]);
            foreach ($data['goods_list'] as $item){
                $orderGoodsData[] = [
                    'order_no' => Date('YmdHis').rand(000000,999999),
                    'sku' => $item['sku'],
                    'library' => $item['library'],
                    'num' => $item['num'],
                    'variety_index' => $item['variety_index'],
                    'variety_name' => $item['variety_name'],
                    'order_id' => $order->id
                ];
            }
            $OrdersGoods = new OrdersGoods();
            $OrdersGoods->saveAll($orderGoodsData);
            Db::commit();
            return $order ? $order->id : false;
        } catch (\Exception $e) {
            // 回滚事务
            Db::rollback();
            return $e->getMessage();
        }
    }

    /**
     * 更新第三方订单号
     * @return void
     */
    public static function updateOrderNo($order_no,$order_sn)
    {
        Db::startTrans();
        try {
            $result = Orders::update(['order_sn'=>$order_sn],['order_no'=>$order_no]);
            Db::commit();
            return $result ? true : false;
        } catch (\Exception $e) {
            // 回滚事务
            Db::rollback();
            return $e->getMessage();
        }
    }
}
